package com.example.demo;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

/**
 * @author lin_c
 * @Description: https://www.jianshu.com/p/6341014659f2?utm_campaign=maleskine
 * https://blog.csdn.net/ol_beta/article/details/5926451
 * @date 2018年11月21日 上午9:25:31
 */
public class WordToPDF1 {  
    
    public static void main(String[] args) throws Exception {
    	String filepath = "D:/Develop/";
        String docpath = "D:/Develop/上海昊沧保养报告 (28).docx";  
        String outpath = "D:/Develop/我是结果.pdf";
           
        String picPath = filepath + "/image/";
        File picFile = new File(picPath);
        String content = null;
        
        FileInputStream in = new FileInputStream(new File(docpath));
        
        XWPFDocument document = new XWPFDocument(in);
        XHTMLOptions options = XHTMLOptions.create();
        options.setExtractor(new FileImageExtractor(picFile));
        options.URIResolver(new BasicURIResolver(picPath));
        
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, bos, options);
        bos.close();
        content = bos.toString();
        System.out.println(content);
        System.err.println("---------------------------");
        
        FileOutputStream fos = null;
        String outpathHtml = "D:/Develop/"+"1111.html";
        BufferedWriter bw = null;
        try {
        Document doc = Jsoup.parse(content);
        content = doc.html();
        content = content.replaceAll("<br>", "<br></br>");
        // content = content.getBytes("UTF-8").toString();
        System.out.println(content);
        File file = new File(outpathHtml);
        fos = new FileOutputStream(file);
        bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
        bw.write(content);
        }catch(Exception e) {
        	e.printStackTrace();
        }finally {
			try {
				if(bw != null) {
					bw.close();
				}
				if(fos != null) {
					fos.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
      //加载字体
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider() {

            @Override
            public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
                // log.debug("fontname:{},size:{},encoding:{},embedded:{},style:{},color:{}",fontname,size,encoding,embedded,style,color == null ? null : color.toString());

                //你的字体文件的位置
                //这里把所有字体都设置为宋体了,可以根据fontname的值设置字体
                // String yaHeiFontName ="C:/windows/fonts/simsun.ttc";
            	String yaHeiFontName ="/SIMSUN.TTC";
                //如果是ttc需要这一行,ttf不需要
                yaHeiFontName += ",1";
                Font yaHeiFont;
                Font font = null;
                try {
                     font = new Font(BaseFont.createFont(yaHeiFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
                    font.setStyle(style);
                    font.setColor(color);
                    if (size>0){
                        font.setSize(size);
                    }
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return font;
            }
        };
        com.itextpdf.text.Document document1 = new com.itextpdf.text.Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document1, new FileOutputStream(outpath));
        document1.open();
        XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document1, new FileInputStream(outpathHtml),Charset.forName("UTF-8"),fontProvider);
        document1.close();
        System.out.println("------------转换成功------------");
	}
    
}  